package com.springmvc.interceptor;

import com.springmvc.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();

        if(uri.indexOf("login") > 0 || uri.indexOf("doLogin")>0 || uri.indexOf("register")>0 || uri.indexOf("doRegister")>0){
            return true;
        }

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){//如果session中没有user 说明没有登陆过
            response.sendRedirect("/login");//重定向到登录页
            return false;
        }else{
            return true;
        }
    }
}
